//
//  BKXOAuthController.swift
//  微博
//
//  Created by 田凯 on 16/4/18.
//  Copyright © 2016年 田凯. All rights reserved.
//

import UIKit
import SVProgressHUD
class BKXOAuthController: UIViewController {

    //https://api.weibo.com/oauth2/authorize
    override func loadView() {
        
        view = webView
        // 设置代理
        webView.delegate = self
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(REDIRECT_RRI)")
        
//        print(url)
        let request = NSURLRequest(URL: url!)
       
        webView.loadRequest(request)
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setUI()
    }
    func setUI(){
        view.backgroundColor = UIColor.whiteColor()
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancle")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "auto")
        navigationItem.title = "微博登陆"
    
    }
    // MARK: - 导航栏点击事件
    func cancle(){
    dismissViewControllerAnimated(true, completion: nil)
    }
    func auto(){
//    print("自动填充")
        //document.getElementById('userId').value='test';document.getElementById('passwd').value='hhh'
        let jsString = "document.getElementById('userId').value='\(weiboName)';document.getElementById('passwd').value='\(weiboPwd)'"
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)

    
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // MARK: - 懒加载webview
    lazy var webView: UIWebView = UIWebView()

    }

extension BKXOAuthController: UIWebViewDelegate{
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
       //        let urlString = request.URL?.absoluteString
        if let urlString = request.URL?.absoluteString where urlString.hasPrefix(REDIRECT_RRI){
//        print(urlString)
//            let p = request.URL?.query
//            print(p)
            if let p = request.URL?.query{
//                print(p)
                let code = p.substringFromIndex("code=".endIndex)
//                print(code)
                //获取accessToken 
                getAccessToken(code)
            
            }
       
            
        }

        return true

}
}
//分类 方法
extension BKXOAuthController{

//获取access-token
    func getAccessToken(code: String){
    // https://api.weibo.com/oauth2/access_token
        let urlString: String = "https://api.weibo.com/oauth2/access_token"
    //参数
       let paramet = [
        "client_id": APPKEY,
        "client_secret": APPSECRECT,
        "grant_type": "authorization_code",
        "code": code,
        "redirect_uri":REDIRECT_RRI
        
        ]
        BKXNetworkTools.sharedTools.request(RequestMethed.POST, urlString: urlString, paramerent: paramet) { (reponce, error) -> () in
            if error != nil{
            print(error)
            return
            }
            guard let dict = reponce as? [String: AnyObject] else{
            
            return
            }
            let account = BKXUserAccount(dict: dict)
            
            
            
            self.getUsreInfo(account)
        }
    
    }
    
    
    //获取用户信息
    func getUsreInfo(account: BKXUserAccount){
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        //参数
        let  paramet = [
        "access_token": account.access_token!,
            "uid":account.uid!

            
        ]
    //发送网络请求
        BKXNetworkTools.sharedTools.request(RequestMethed.GET, urlString: urlString, paramerent: paramet) { (reponce, error) -> () in
            if error != nil{
             print(error)
            return
            
            }
            
            guard let dict = reponce as? [String: AnyObject] else{
            
          return
            }
            
            print(dict)
            
            account.profile_image_url = dict["profile_image_url"] as? String
            account.name = dict["name"] as? String
            //将用户数据保存
            BKXUserAccountTools.sharedUserAccountTools.saveUserAccount(account)
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
                // 发送通知  切换根视图
                NSNotificationCenter.defaultCenter().postNotificationName(SwitchDefaultVcNSNotification, object: nil)
                
                
                
            })
            
            
        }
    
    
    }
    
    
    

}
















